#include<wx/wx.h>
#include "Server.h"
#include "Frame.h"


Server::Server()
{
	wxIPV4address addr;
	addr.Service(3000);
	m_server=new wxSocketServer(addr);
	sock=new wxSocketBase();
	_sahovskaPloca=new SahovskaPloca();
}

void Server::init()
{		
	if (!m_server->Ok())
	{
		m_frame->displayInfo->AppendText(_("Could not listen at the specified port !"));
		return;
	 }
	else
	{
		m_frame->displayInfo->AppendText(_("Server listening."));
	}
	m_server->SetEventHandler(*this,SERVER_ID);
	m_server->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
	m_server->Notify(true);
}
bool Server::GetStatus()
{
	if (!m_server->Ok())
	{
		return false;
	 }
	else
	{
		return true;
	}
}
void Server::SetFrame(Frame *frame)
{
	m_frame=frame;
}

void Server::OnSocketEvent(wxSocketEvent& event)
{
	#define MAX_MSG_SIZE 20
	m_frame->displayInfo->AppendText(_("OnSocketEvent.\n\n"));
	wxString s = _("OnSocketEvent: ");
	sock = event.GetSocket();
	int buf[4];
  // testiranje veze
	if(sock->IsConnected())
	{
	m_frame->displayInfo->AppendText(s);
   switch(event.GetSocketEvent())
   {
   case wxSOCKET_CONNECTION:
	   break;
    case wxSOCKET_INPUT:
    {
		int buf[4];
		sock->Read(buf,sizeof(buf));
		if(buf[0]>8)
		{
				wxString s1;
				wxChar *buf = new wxChar[500];
				wxUint32 len;
				len = sock->ReadMsg(buf, 500 * sizeof(wxChar)).LastCount();
				s1.Printf(_("\nClient says: %s"), buf);
				m_frame->chatText->AppendText(s1);
				delete []buf;
		}
		if(buf[0]<=8)
		{
			wxString s1;
				
				s1.Append("\nwxSOCKET_INPUT");
				m_frame->displayInfo->AppendText(s1);
				//sock->Read(buf,sizeof(buf));
				m_frame->NewMove((int)buf[0]-1,(int)buf[1]-1, (int)buf[2]-1, (int)buf[3]-1);
				m_frame->displayInfo->AppendText("\nData reciving from Server");
				m_frame->displayInfo->AppendText(wxString::Format(wxT("\n%d %d %d %d"), (int)buf[0],(int)buf[1], (int)buf[2], (int)buf[3]));
				m_frame->Refresh(true,0);
				//delete []buf;
		}
	}

	case wxSOCKET_OUTPUT:

		break;
	  case wxSOCKET_LOST:
    {
      sock->Destroy();
      break;
    }
    default: ;
  }
	}

#undef MAX_MSG_SIZE
	
}
void Server::OnServerEvent(wxSocketEvent& event)
{

	wxString s = _("OnServerEvent: ");
	//wxSocketBase* sock = event.GetSocket();
  switch(event.GetSocketEvent())
  {
    case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
	case wxSOCKET_LOST	:		sock->Destroy(); break;
    default                  : s.Append(_("Unexpected event !\n")); break;
  }
  m_frame->displayInfo->AppendText(s);
  // Accept new connection if there is one in the pending
  // connections queue, else exit. We use Accept(false) for
  // non-blocking accept (although if we got here, there
  // should ALWAYS be a pending connection).
  sock = m_server->Accept(false);
  if (sock)
  {
    m_frame->displayInfo->AppendText(_("New client connection accepted\n\n"));
  }
  else
  {
    m_frame->displayInfo->AppendText(_("Error: couldn't accept a new connection\n\n"));
    return;
  }
	sock->SetEventHandler(*this,SOCKET_ID);
	sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
	sock->Notify(true);

}
Server::~Server()
{
	m_server->Close();
	sock->Close();
	delete m_server;
	delete m_frame;
	delete _sahovskaPloca;
	delete sock;
}

void Server::SendCoord(int x1, int y1,int x2,int y2)
{
	int buf[4];
	buf[0]=x1;
	buf[1]=y1;
	buf[2]=x2;
	buf[3]=y2;
	sock->Write(buf,sizeof(buf));
	if(sock->IsConnected())
		m_frame->displayInfo->AppendText("\nServer data sent");
	
}

bool Server::IsConnected()
{
	if(sock->IsConnected())
		return true;
	else	return false;
}

void Server::SendText(wxString text)
{
	const wxChar *msg1;
	//m_clientSoc->SetFlags(wxSOCKET_WAITALL);
	int buf[4];
	buf[0]=9;
	sock->Write(buf,sizeof(buf));
	size_t len;
	msg1 = text.c_str();
	len  = (wxStrlen(msg1) + 1) * sizeof(wxChar);
	sock->WriteMsg(msg1,len);

	
}
void Server::RcvCoord(wxSocketBase *sock)
{
	
}

wxSocketBase *Server::GetSocket()
{
	return sock;
}
BEGIN_EVENT_TABLE(Server, wxEvtHandler)
	EVT_SOCKET(SOCKET_ID, Server::OnSocketEvent)
	EVT_SOCKET(SERVER_ID, Server::OnServerEvent)
END_EVENT_TABLE()